package com.geline.luckysheet.controller;

import com.geline.luckysheet.util.EasyExcelUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.core.io.ClassPathResource;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;

/**
 * @author: mengxin
 * @date: 2022/10/15 11:33
 */
@RestController
@Slf4j
public class ExportController {

    /**
     * 根据实体类导出
     * localhost:9501/excel/export
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) {
        List<ExcelDemo> beanList = new ArrayList<>();
        beanList.add(new ExcelDemo(1, "小张852134567", 20, new Date()));
        beanList.add(new ExcelDemo(2, "小黄952147830", 30, new Date()));
        beanList.add(new ExcelDemo(3, "小李", 25, new Date()));
        EasyExcelUtil.downExcelByClass(response, beanList, "标题", ExcelDemo.class);
    }

    /**
     * 根据模板导出
     * localhost:9501/excel/exportByTemplate
     * @param response
     * @throws IOException
     */
    @GetMapping("/exportByTemplate")
    public void exportByTemplate(HttpServletResponse response) throws IOException {
        Map<String, Object> map = new HashMap<>();
        map.put("title", "测试导出Excel-Demo");
        map.put("user_count", 5600);
        map.put("user_name", "赵小相");
        List<ExcelDemo> beanList = new ArrayList<>();
        beanList.add(new ExcelDemo(1, "小张852134567", 20, new Date()));
        beanList.add(new ExcelDemo(2, "小黄952147830", 30, new Date()));
        beanList.add(new ExcelDemo(3, "小李", 25, new Date()));
        EasyExcelUtil.downExcelByComplexFill(response, getTemplate(), "标题", map, beanList);
    }

    private InputStream getTemplate() throws IOException {
        ClassPathResource resource = new ClassPathResource("templates/demo.xlsx");
        //log.debug("resource = {}", resource.getFile().getAbsoluteFile());
        return resource.getInputStream();
    }
}
